package com.zijing2333.adaptivescheduling.switchCondition.util;

import android.app.ActivityManager;
import android.content.Context;
import android.os.Debug;
import android.os.Environment;
import android.os.StatFs;

import java.io.File;

public class MemoryUtil {

    /**
     * 获取设备总内存大小
     *
     * @param context 上下文
     * @return 总内存大小，单位为字节
     */
    public static long getTotalMemory(Context context) {
        ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        activityManager.getMemoryInfo(memoryInfo);
        return memoryInfo.totalMem;
    }

    /**
     * 获取设备可用内存大小
     *
     * @param context 上下文
     * @return 可用内存大小，单位为字节
     */
    public static long getAvailableMemory(Context context) {
        ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        activityManager.getMemoryInfo(memoryInfo);
        return memoryInfo.availMem;
    }

    /**
     * 获取当前应用程序占用的内存大小
     *
     * @param context 上下文
     * @return 当前应用程序占用的内存大小，单位为字节
     */
    public static long getUsedMemory(Context context) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        int pid = android.os.Process.myPid();
        Debug.MemoryInfo memoryInfo = activityManager.getProcessMemoryInfo(new int[]{pid})[0];
        return memoryInfo.getTotalPrivateDirty() * 1024;
    }

    /**
     * 获取设备存储空间总大小
     *
     * @return 存储空间总大小，单位为字节
     */
    public static long getTotalStorage() {
        File path = Environment.getDataDirectory();
        StatFs statFs = new StatFs(path.getPath());
        long blockSize = statFs.getBlockSizeLong();
        long totalBlocks = statFs.getBlockCountLong();
        return blockSize * totalBlocks;
    }

    /**
     * 获取设备可用存储空间大小
     *
     * @return 可用存储空间大小，单位为字节
     */
    public static long getAvailableStorage() {
        File path = Environment.getDataDirectory();
        StatFs statFs = new StatFs(path.getPath());
        long blockSize = statFs.getBlockSizeLong();
        long availableBlocks = statFs.getAvailableBlocksLong();
        return blockSize * availableBlocks;
    }

    /**
     * 获取设备清理后台进程的内存阙值
     * @param context
     * @return
     */
    public static long getMemoryThreshold(Context context) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
        activityManager.getMemoryInfo(memoryInfo);
        return memoryInfo.threshold;
    }
}